<?php

class StudentController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();
        $permissionActions = array("edit", "admin","editadmin");
        if(!$auth->hasIdentity())
        {
            if( in_array($this->_request->getActionName(), $permissionActions))
            {
                $this->_redirect('student/login');
            }
        }
        else
        {
            $infoUser = $auth->getIdentity();
            $this->view->student = $infoUser;
        }
        
    }

    public function indexAction()
    {
        // action body
        $this->view->title = "Trang chủ";
        $mstudent = new Application_Model_Students();

        $totalStudents = $mstudent->countStudents();
        $this->view->totalStudents = $totalStudents;

        $totalTeached = $mstudent->countTeached();
        $this->view->totalTeached = $totalTeached;
        
        if($this->getRequest()->isPost())
        {
            $this->view->school = $_POST['school'];
            $school = $_POST['school'];
            $gender = $_POST['gender'];
            $class = $_POST['class'];
            
            $adapter = new Zend_Paginator_Adapter_DbSelect($mstudent->listStudents($school, $class, $gender));
        }
        else
        {
            $adapter = new Zend_Paginator_Adapter_DbSelect($mstudent->listall());
        }
        $paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(15);
        $paginator->setPageRange(10);
        $currentPage = $this->_request->getParam('page',1);
        $paginator->setCurrentPageNumber($currentPage);
        $this->view->data = $paginator;
        
        

    }

    public function loginAction()
    {
        // action body
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flashmsgs = $flashMessenger->getMessages();

        $students = new Application_Model_Students();
        $this->view->title = "Đăng Nhập";
        $form = new Application_Form_Login();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $data = $form->getValues();
                $auth = Zend_Auth::getInstance();
                $authAdapter = new Zend_Auth_Adapter_DbTable($students->getAdapter(), 'students');
                $authAdapter->setIdentityColumn('email')
                        ->setCredentialColumn('password')
                        ->setCredentialTreatment('SHA1(CONCAT(?,salt))');
                
                $authAdapter->setIdentity($data['email'])
                        ->setCredential($data['password']);
                
                $result = $auth->authenticate($authAdapter);
                
                if ($result->isValid()) {
                    $dataResult = $authAdapter->getResultRowObject();
                    $auth->getStorage()->write($dataResult);
                    if ($dataResult->priviledge == 0) {
                        $this->_redirect('student/index');
                    } else {
                        $this->_redirect('student/admin');
                    }
                } else {
                    $this->view->wrongAccountMessage = "Sai email hoặc mật khẩu. Vui lòng thử lại.";
                }
            }
        }
        $this->view->form = $form;
    }

    public function registerAction()
    {
        // action body
        $this->view->title = "Đăng Ký";
        $students = new Application_Model_Students();
        $form = new Application_Form_Register();

        $this->view->errorFormMessage = null;
       
        if($this->getRequest()->isPost())
        {
            if($form->isValid($_POST))
            {
                if ($_POST['password'] != $_POST['confirmpassword']) {
                    $this->view->errorMessage = "Xác nhận mật khẩu không đúng.";
                } else if ($_POST['checkbox'] != 1) {
                    $this->view->errorCheckboxMessage = "Bạn chưa đồng ý điều khoản sử dụng.";
                } else {
                    $data = $form->getValues();
                    if (!is_null($data['avatar'])) {
                        $info = pathinfo($form->avatar->getFileName(null, false));
                        $filename = $info['filename'];
                        $ext = $info['extension'] ? "." . $info['extension'] : "";
                        $newName = $data['phonenumber'] . time() . $ext;
                        $fullPathNameFile = APPLICATION_PATH . '/../public/img/avatars/' . $newName;
                        $filterRename = new Zend_Filter_File_Rename(array('target' => $fullPathNameFile, 'overwrite' => true));
                        $oldName = APPLICATION_PATH . '/../public/img/avatars/' . $filename . $ext;
                        $filterRename->filter($oldName);
                        $data['avatarname'] = $newName;
                    } else {
                        $data['avatarname'] = 'logo.jpg';
                    }

                    $updatedTime = new Zend_Db_Expr('NOW()');
                    $data['updated'] = $updatedTime;

                    $password = $data['password'];
                    $salt = substr(sha1(mt_rand()), 0, 40);
                    $data['password'] = sha1($password . $salt);
                    $data['salt'] = $salt;

                    unset($data['confirmpassword']);
                    unset($data['avatar']);
                    unset($data['captcha']);
                    unset($data['checkbox']);

                    $students->insert($data);

                    //send email to user's friend
                    $email_to = $data['friendemail'];
                    if (!empty($email_to)) {
                        $name_to = 'Bạn của ' . $data['username'];
                        $subject = 'Bạn ' . $data['username'] . ' giới thiệu http:cvgiasu.com cho bạn';
                        $html = "http:cvgiasu.com là website lớn nhất Việt Nam về quản lý hồ sơ gia sư
                    <br>Bạn hãy nhanh chóng tham gia để đăng tải MIỄN PHÍ hồ sơ gia sư của mình và nhận được một công việc gia sư sớm.
                    <hr><br>http:cvgiasu.com.vn, 391 Khương Trung, Thanh Xuân, Hà Nội";
                        $this->sendEmail($email_to, $name_to, $subject, $html);
                    }

                    $this->view->registerSuccessMessage = "Bạn đã đăng ký thành công thông tin gia sư.";
                    $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                    $flashMessenger->addMessage(array('success' => "Bạn đã đăng ký thành công thông tin gia sư!
                    Vui lòng đăng nhập hoặc trở về trang chủ."));
                    $this->_redirect('student/login');
                }
            } else {
                $this->view->errorFormMessage = $form->getMessages();
                if ($_POST['password'] != $_POST['confirmpassword']) {
                    $this->view->errorMessage = "Xác nhận mật khẩu không đúng.";
                }
                if ($_POST['checkbox'] != 1) {
                    $this->view->errorCheckboxMessage = "Bạn chưa đồng ý điều khoản sử dụng.";
                }
            }
        }
        $this->view->form = $form;
        
    }

    public function editAction()
    {
        // action body   
        $auth = Zend_Auth::getInstance();
        $infoUser = $auth->getIdentity();

        $students = new Application_Model_Students();
        $updatedStudent = $students->findStudentById($infoUser->id);
        $this->view->student = $updatedStudent;

        $this->view->title = "Cập nhật thông tin tài khoản";
        $form = new Application_Form_Edit();
        
        $form->getElement('username')->setValue($updatedStudent->username);
        $form->getElement('gender')->setValue($updatedStudent->gender);
        $form->getElement('email')->setValue($updatedStudent->email);
        $form->getElement('phonenumber')->setValue($updatedStudent->phonenumber);
        $form->getElement('city')->setValue($updatedStudent->city);
        $form->getElement('district')->setValue($updatedStudent->district);
        $form->getElement('school')->setValue($updatedStudent->school);
        $form->getElement('year')->setValue($updatedStudent->year);
        $form->getElement('subjects')->setValue($updatedStudent->subjects);
        $form->getElement('teachtime')->setValue($updatedStudent->teachtime);
        $form->getElement('salary')->setValue($updatedStudent->salary);
        $form->getElement('fromclass')->setValue($updatedStudent->fromclass);
        $form->getElement('toclass')->setValue($updatedStudent->toclass);
        $form->getElement('description')->setValue($updatedStudent->description);
        $form->getElement('award')->setValue($updatedStudent->award);

        //form update avatar
        $avatarForm = new Application_Form_AvatarUpload();

        date_default_timezone_set('Asia/Bangkok');
        //check not teach
        $updateTime = $updatedStudent->updated;
        $interval = time()- strtotime($updateTime);
        $elapse = 86400 - $interval;
        if($elapse < 0)
        {
            $this->view->elapse = -1;
        }
        else
        {
            $this->view->elapse = $elapse;
        }    
        
        if($interval > 86400)
        {
            $this->view->checkNotTeach = 1;
        }
        else
        {
            $this->view->checkNotTeach = 0;
        }
        //check teached
        $this->view->status = $updatedStudent->status;
              
        if ($this->getRequest()->isPost()) {
            if (isset($_POST['update'])) {
                if ($_POST['update'] == 'Cập nhật') {
                    if (strcmp($_POST['email'], $updatedStudent->email) == 0) {
                        unset($_POST['email']);
                    }
                    if (strcmp($_POST['phonenumber'], $updatedStudent->phonenumber) == 0) {
                        unset($_POST['phonenumber']);
                    }
                    if ($form->isValidPartial($_POST)) {
                        if ($_POST['password'] != $_POST['confirmpassword']) {
                            $this->view->errorMessage = "Xác nhận mật khẩu không đúng.";
                        } else {
                            $data = $form->getValues();
                            if (empty($_POST['password']) && empty($_POST['confirmpassword'])) {
                                unset($data['password']);
                                unset($data['confirmpassword']);
                            } else {
                                $password = $data['password'];
                                $salt = substr(sha1(mt_rand()), 0, 40);
                                $data['password'] = sha1($password . $salt);
                                $data['salt'] = $salt;
                            }
                            unset($data['confirmpassword']);

                            $where = 'id= ' . $updatedStudent->id;
                            $students->update($data, $where);
                            $this->view->editSuccess = "Cập nhật thành công!!!";
                        }
                    } else {
                        $this->view->errorFormMessage = $form->getMessages();
                    }
                }
                else if($_POST['update'] == 'Cập nhật ảnh')
                {
                    if($avatarForm->isValid($_POST))
                    {
                        $info = pathinfo($avatarForm->avatar->getFileName(null, false));
                        $filename = $info['filename'];
                        $ext = $info['extension']?".".$info['extension']:"";
                        //upload picture
                        $data = $avatarForm->getValues();
                        
                        $newName = $infoUser->phonenumber.time().$ext;
                        $fullPathNameFile = APPLICATION_PATH.'/../public/img/avatars/'.$newName;
                        
                        //rename uploaded picture
                        $filterRename = new Zend_Filter_File_Rename(array('target' => $fullPathNameFile, 'overwrite' => true));
                        $oldName = APPLICATION_PATH.'/../public/img/avatars/'.$filename.$ext;
                        $filterRename->filter($oldName);

                        $where = 'id= '.$updatedStudent->id;
                        $students->update(array('avatarname' => $newName), $where);

                        $this->_redirect('student/edit');
                    }

                }  
                          
            }
        }

        $this->view->form = $form;
        $this->view->avatarForm = $avatarForm;

        if($this->getRequest()->isXmlHttpRequest())
        {
            $commad = $this->getRequest()->getParam('command');
            $timeNow = new Zend_Db_Expr('NOW()');

            if(strcmp($commad, 'notTeach') == 0)
            {
                $where = 'id= '.$infoUser->id;
                $students->update(array('updated' => $timeNow,'status' => '0'), $where);
            }
            if(strcmp($commad, 'Teached') == 0 )
            {
                $where = 'id= '.$infoUser->id;
                $students->update(array('status' => '1'), $where);
            }
        }
    }

    public function logoutAction()
    {
        // action body
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('student/index');
    }

    public function hubAction()
    {
        // action body
        $this->view->title = "Thông tin chi tiết";

        $studentid = $this->getRequest()->getParam('studentid');
        $this->view->studentid = $studentid;
        $mstudent = new Application_Model_Students();
        $data = $mstudent->findStudentById($studentid);

        $this->view->row = $data;

        if ($this->_request->isXmlHttpRequest()) {
            $parents = new Application_Model_Parents();
            $parentName = $this->getParam('parentname');
            $parentNumber = $this->getParam('parentnumber');
            $parentAddress = $this->getParam('parentaddress');
            $parentClass = $this->getParam('parentclass');

            if (trim($parentName) && trim($parentNumber)) {
                $email_to = "cvgiasu@gmail.com";
                $name_to = "CVgiasu.com";
                $subject = "Thông tin phụ huynh chọn gia sư";
                $html = "Họ tên phụ huynh: " . $parentName .
                        "<br>Học sinh lớp: " . $parentClass .
                        "<br>Số điện thoại: " . $parentNumber .
                        "<br>Địa chỉ: " . $parentAddress;
                $this->sendEmail($email_to, $name_to, $subject, $html);

                echo 1;
                exit;
            }
            else
            {
                echo 0;
            }
        }
    }

    public function forgetAction()
    {
        // action body
        $this->view->title = "Quên mật khẩu";
        //send email
        
        if($this->getRequest()->isPost())
        {
            $emailAdress = $_POST['email'];
            $mstudent = new Application_Model_Students();
            $student = $mstudent->findStudentByEmail($emailAdress);

            $email_to = $emailAdress;
            $name_to = $student->username;

            $subject = 'Cung cấp thông tin tài khoản';
            $html = "Thông tin tài khoản: 
                    <br>Email: ".$emailAdress.
                    "<br>Mật khẩu: ".$student->password.
                    "<br><hr><b>http://cvgiasu.com, 391 Khương Trung, Thanh Xuân, Hà Nội</b>";

            $this->sendEmail($email_to, $name_to, $subject, $html);
            
            $this->redirect('student/login');
        }
    }

    public function sendEmail($email_to, $name_to, $subject, $html)
    {
        $settings = array('ssl' => 'ssl','port' => '465','auth'=>'login','username' => 'cvgiasu@gmail.com','password' => 'cvgiasu2012');
        $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $settings);

        $email_from = "cvgiasu@gmail.com";
        $name_from = "CVgiasu.com";

        $mail = new Zend_Mail('UTF-8');
        $mail->setReplyTo($email_from, $name_from);
        $mail->setFrom($email_from, $name_from);
        $mail->addTo($email_to, $name_to);
        $mail->setSubject($subject);
        $mail->setBodyHtml($html);
        $mail->send($transport);

    }

    public function statAction()
    {
        // action body
         $this->view->title = "Thống kê";

         $mstudent = new Application_Model_Students();

        $countSchools = array();
        $hanoiSchool = Zend_Registry::get('hanoiSchools');
        foreach ($hanoiSchool as $key => $value) {
            $number = $mstudent->countStudentsBySchool($key);
            array_push($countSchools, $number);
        }       
        $this->view->countSchools = $countSchools;      
    }

    public function adminAction()
    {
        // action body
        $this->view->title = "Trang chủ";
        $mstudent = new Application_Model_Students();
        
        if($this->getRequest()->isXmlHttpRequest())
        {
            $commad = $this->getRequest()->getParam('command');
            $id = $this->getRequest()->getParam('id');
            $student = $mstudent->findStudentById($id);
            $status = $student['status'];
            $where = 'id = '.$id;
            $updatedTime = new Zend_Db_Expr('NOW()');
            
            if(strcmp($commad, 'endisable') == 0)
            {
               if($status == 0)
                {
                    $mstudent->update(array('status' => '1','updated' => $updatedTime), $where);
                    echo 1;
                    exit;
                }
                else
                {
                    $mstudent->update(array('status' => '0','updated' => $updatedTime), $where);
                    echo 0;
                    exit;
                }
            }
        }
        //paginate page for student list
        $adapter = new Zend_Paginator_Adapter_DbSelect($mstudent->listAllForAdmin());
        $paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(10);
        $paginator->setPageRange(10);
        $currentPage = $this->_request->getParam('page',1);
        $paginator->setCurrentPageNumber($currentPage);
        $this->view->data = $paginator;
    }

    public function editadminAction()
    {
        // action body
        $studentid = $this->getRequest()->getParam('studentid');
        
        $students = new Application_Model_Students();
        $updatedStudent = $students->findStudentById($studentid);
        $this->view->studentAdmin = $updatedStudent;

        $this->view->title = "Cập nhật thông tin cho sinh viên";
        $form = new Application_Form_Edit();

        $form->getElement('username')->setValue($updatedStudent->username);
        $form->getElement('gender')->setValue($updatedStudent->gender);
        $form->getElement('email')->setValue($updatedStudent->email);
        $form->getElement('phonenumber')->setValue($updatedStudent->phonenumber);
        $form->getElement('city')->setValue($updatedStudent->city);
        $form->getElement('district')->setValue($updatedStudent->district);
        $form->getElement('school')->setValue($updatedStudent->school);
        $form->getElement('year')->setValue($updatedStudent->year);
        $form->getElement('subjects')->setValue($updatedStudent->subjects);
        $form->getElement('teachtime')->setValue($updatedStudent->teachtime);
        $form->getElement('salary')->setValue($updatedStudent->salary);
        $form->getElement('fromclass')->setValue($updatedStudent->fromclass);
        $form->getElement('toclass')->setValue($updatedStudent->toclass);
        $form->getElement('description')->setValue($updatedStudent->description);
        $form->getElement('award')->setValue($updatedStudent->award);

        $this->view->form = $form;
        
        if($this->getRequest()->isPost())
        {           
                    if(strcmp($_POST['email'], $updatedStudent->email) == 0)
                    {
                        unset ($_POST['email']);
                    }
                    if(strcmp($_POST['phonenumber'], $updatedStudent->phonenumber) == 0)
                    {
                        unset ($_POST['phonenumber']);
                    }
                    if($form->isValidPartial($_POST))
                    {
                        $data = $form->getValues();
                        if (empty($_POST['password']) && empty($_POST['confirmpassword'])) {
                            unset($data['password']);
                            unset($data['confirmpassword']);
                        }
                        else if($data['password'] != $data['confirmpassword'])
                        {
                            $this->view->errorMessage = "Xác nhận mật khẩu không đúng.";
                            return;
                        }
                        else{
                            $password = $data['password'];
                            $salt = substr(sha1(mt_rand()), 0,40);
                            $data['password'] = sha1($password.$salt);
                            $data['salt'] = $salt;
                        }
                        unset($data['confirmpassword']);

                        $where = 'id= '.$updatedStudent->id;
                        $students->update($data, $where);
                    }
                    else
                    {
                        $this->view->errorFormMessage = $form->getMessages();
                        return;
                    }                         
        }
    }
    public function recommendAction()
    {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $email_to = $this->getRequest()->getParam('email');
            if (!empty($email_to)) {
                $name_to = 'Bạn của ' . $data['username'];
                $subject = 'Bạn ' . $data['username'] . ' giới thiệu http:cvgiasu.com cho bạn';
                $html = "http:cvgiasu.com là website lớn nhất Việt Nam về quản lý hồ sơ gia sư
                    <br>Bạn hãy nhanh chóng tham gia để đăng tải MIỄN PHÍ hồ sơ gia sư của mình và nhận được một công việc gia sư sớm.
                    <hr><br>http:cvgiasu.com.vn, 391 Khương Trung, Thanh Xuân, Hà Nội";
                $this->sendEmail($email_to, $name_to, $subject, $html);
            }
        }
    }
}





















